<?php
declare (strict_types = 1);

namespace app\middleware;

use app\common\service\TokenService;
use app\dto\R;

class Check
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取请求头中的token
        $token = $request->header('Authorization');
        
        // 判断token是否存在
        if (!$token) {
            return json(R::result(401, "请先登录后再访问"))->code(401);
        }
        
        // 验证token
        $tokenService = new TokenService();
        $checkResult = $tokenService->verifyToken($token);
        
        if (!$checkResult) {
            return json(R::result(401, "Token无效或登录超时"))->code(401);
        }
        
        // 将用户ID存入请求中，方便后续使用 
        $request->userId = $checkResult['user_id'];
        
        return $next($request);
    }
}
